import os
import time
import logging
import tkinter
from src.ui.base import CustomsApp

def setup_logging():
    """ 配置日志系统 """
    if not os.path.exists('logs'):
        os.makedirs('logs')

    # 先只配置文件和控制台日志，UI日志在CustomsApp中添加
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(levelname)s - %(message)s',
        handlers=[
            logging.FileHandler('logs/customs_signer.log', encoding='utf-8'),
            logging.StreamHandler()
        ]
    )

def main():
    """ 主函数 """
    setup_logging()
    logging.info("海关加签程序启动")

    # 创建主窗口
    root = tkinter.Tk()
    app = CustomsApp(root)

    # 设置窗口属性
    root.title("海关加签客户端 v1.0")
    root.geometry("800x600")
    root.resizable(True, True)

    try:
        root.mainloop()
    except KeyboardInterrupt:
        logging.info("程序被用户中断")
    except Exception as e:
        logging.error(f"程序异常: {e}")
    finally:
        # 先移除所有日志处理器，再执行清理
        for handler in logging.getLogger().handlers[:]:
            logging.getLogger().removeHandler(handler)
        app.cleanup()
        # 最后一条日志直接写入文件，避免UI问题
        with open('logs/customs_signer.log', 'a', encoding='utf-8') as f:
            f.write(f"{time.strftime('%Y-%m-%d %H:%M:%S')} - INFO - 海关加签程序退出\n")

if __name__ == "__main__":
    main()